package com.example.rustfs.service;

import com.example.rustfs.dao.RecentFileDao;
import com.example.rustfs.dto.FileInfo;
import com.example.rustfs.entity.RecentFile;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 最近使用文件服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RecentFileService {
    
    private final RecentFileDao recentFileDao;
    private static final int MAX_RECENT_FILES = 50;
    
    /**
     * 添加最近访问记录
     */
    public void addRecentFile(Long userId, String fileKey, String fileName, Long fileSize) {
        RecentFile recentFile = new RecentFile();
        recentFile.setUserId(userId);
        recentFile.setFileKey(fileKey);
        recentFile.setFileName(fileName);
        recentFile.setFileSize(fileSize);
        recentFile.setFileType(getFileType(fileName));
        recentFile.setAccessTime(LocalDateTime.now());
        
        recentFileDao.save(recentFile);
        log.debug("添加最近访问记录: {}", fileName);
    }
    
    /**
     * 获取用户最近使用的文件
     */
    public List<FileInfo> getRecentFiles(Long userId, int limit) {
        List<RecentFile> recentFiles = recentFileDao.findByUserId(userId, Math.min(limit, MAX_RECENT_FILES));
        List<FileInfo> fileInfoList = new ArrayList<>();
        
        for (RecentFile rf : recentFiles) {
            FileInfo fileInfo = new FileInfo();
            fileInfo.setName(rf.getFileName());
            fileInfo.setKey(rf.getFileKey());
            fileInfo.setSize(rf.getFileSize());
            fileInfo.setLastModified(rf.getAccessTime().atZone(java.time.ZoneId.systemDefault()).toInstant());
            fileInfo.setType("file");
            fileInfo.setIcon(getFileIcon(rf.getFileName()));
            fileInfo.setFormattedSize(formatFileSize(rf.getFileSize()));
            fileInfoList.add(fileInfo);
        }
        
        return fileInfoList;
    }
    
    /**
     * 删除最近访问记录
     */
    public void removeRecentFile(Long userId, String fileKey) {
        recentFileDao.deleteByFileKey(userId, fileKey);
    }
    
    private String getFileType(String fileName) {
        if (fileName == null || !fileName.contains(".")) {
            return "unknown";
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    }
    
    private String getFileIcon(String fileName) {
        String ext = getFileType(fileName);
        return switch (ext) {
            case "pdf" -> "bi-file-earmark-pdf-fill";
            case "doc", "docx" -> "bi-file-earmark-word-fill";
            case "xls", "xlsx" -> "bi-file-earmark-excel-fill";
            case "ppt", "pptx" -> "bi-file-earmark-ppt-fill";
            case "jpg", "jpeg", "png", "gif", "bmp", "webp", "svg" -> "bi-file-earmark-image-fill";
            case "zip", "rar", "7z", "tar", "gz" -> "bi-file-earmark-zip-fill";
            case "txt", "md" -> "bi-file-earmark-text-fill";
            case "mp4", "avi", "mov", "wmv", "flv", "mkv", "webm", "ogv" -> "bi-file-earmark-play-fill";
            case "mp3", "wav", "flac", "aac", "ogg", "oga", "m4a", "wma", "opus" -> "bi-file-earmark-music-fill";
            case "java", "js", "py", "cpp", "c", "html", "css", "json", "xml" -> "bi-file-earmark-code-fill";
            default -> "bi-file-earmark-fill";
        };
    }
    
    private String formatFileSize(long size) {
        if (size <= 0) return "0 B";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.##").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
}

